package recycle.controller;

import io.vertx.core.MultiMap;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import recycle.common.ResponseHandler;
import recycle.pojo.Station;
import recycle.service.StationService;

public class StationController {
    private final StationService stationService;

    public StationController(StationService stationService) {
        this.stationService = stationService;
    }

    public void setupRoutes(Router router) {

        router.post("/stations/create").handler(this::create);
        router.delete("/stations/delete/:id").handler(this::delete);
        router.put("/stations/update").handler(this::update);
        router.put("/stations/clear/:id").handler(this::clear);
        router.get("/stations/details/:id").handler(this::details);
        router.post("/stations/list").handler(this::list);
    }



    private void create(RoutingContext ctx) {
        Station station = ctx.body().asPojo(Station.class);
        stationService.create(station).onComplete(ResponseHandler.handle(ctx));
    }

    private void list(RoutingContext ctx) {
        Station station = ctx.body().asPojo(Station.class);
        MultiMap params = ctx.request().params();
        Integer pageNum = params.get("pageNum") != null ? Integer.parseInt(params.get("pageNum")) : 1;
        Integer pageSize = params.get("pageSize")!= null ? Integer.parseInt(params.get("pageSize")) : 10;
        stationService.list(station,pageNum,pageSize).onComplete(ResponseHandler.handle(ctx));
    }

    private void details(RoutingContext ctx) {
        Long id = Long.parseLong(ctx.pathParam("id"));
        stationService.details(id).onComplete(ResponseHandler.handle(ctx));
    }


    private void update(RoutingContext ctx) {
        Station station = ctx.body().asPojo(Station.class);
        stationService.update(station).onComplete(ResponseHandler.handle(ctx));
    }

    private void delete(RoutingContext ctx) {
        Long id = Long.parseLong(ctx.pathParam("id"));
        stationService.delete(id).onComplete(ResponseHandler.handle(ctx));
    }

    private void clear(RoutingContext ctx) {
        Long id = Long.parseLong(ctx.pathParam("id"));
        stationService.clear(id).onComplete(ResponseHandler.handle(ctx));
    }
}